#include "Board.h"
#include "Assert.h"
#include <map>

CBoard::CBoard(unsigned int columns, unsigned int rows)
{
	assert(columns%2==0 || rows%2==0);

	m_uColumns	= columns;
	m_uRows			= rows;
	
	GenerateNewGame();
}


bool CBoard::IsInsideRang	(unsigned int i, unsigned int j)
{
	return (m_Tokens.size() > i) && (m_Tokens[i].size() > j);
}


unsigned int CBoard::GetSymbol	(unsigned int column, unsigned int row)
{
	if( IsInsideRang(column, row))
	{
		return m_Tokens[row][column].GetSymbolId();
	}

	return 0;
}


bool CBoard::IsVisible (unsigned int column, unsigned int row)
{
	if( IsInsideRang(column, row))
	{
		return m_Tokens[row][column].IsVisible();
	}
	
	return false;
}


void CBoard::SetVisible (unsigned int column, unsigned int row, bool flag)
{
	if( IsInsideRang(column, row))
	{
		m_Tokens[row][column].SetVisible(flag);
	}
}

void CBoard::GenerateNewGame()
{
	m_Tokens.clear();
	CToken token;
	token.SetSymbolId(999);
	std::vector<CToken> tokens;
	for (unsigned int j = 0; j < m_uColumns; ++j)
	{
		tokens.push_back(token);
	}
	for (unsigned int i = 0; i < m_uRows; ++i)
	{
		m_Tokens.push_back(tokens);
	}
	
	
	//There are m_uColumns*m_uRows/2 symbols
	unsigned int numSymbols = m_uColumns*m_uRows/2;

	std::map<unsigned int, unsigned int> symbols;
	std::map<unsigned int, unsigned int>::iterator itSymbols;
	for(unsigned int i = 0; i < numSymbols; ++i)
	{
		symbols[i] = 0;
	}

	for (unsigned int column = 0; column < m_uColumns; ++column)
	{
		for (unsigned int row = 0; row < m_uRows; ++row)
		{
			bool findSymbol = false;
			unsigned int newSymbol = 0;
			while(!findSymbol)
			{
				newSymbol = rand()%numSymbols;
				itSymbols = symbols.find(newSymbol);
				if(itSymbols->second!=2)
				{
					findSymbol = true;
					itSymbols->second = itSymbols->second + 1;
				}
			}
			m_Tokens[row][column].SetSymbolId(newSymbol);
		}
	}
}

bool CBoard::IsAllVisible ()
{
	for (unsigned int column = 0; column < m_uColumns; ++column)
	{
		for (unsigned int row = 0; row < m_uRows; ++row)
		{
			if (!m_Tokens[row][column].IsVisible()) 
			{
				return false;
			}
		}
	}
	return true;
}